package com.heima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.reggie.common.R;
import com.heima.reggie.domain.Category;
import com.heima.reggie.domain.Dish;
import com.heima.reggie.domain.DishFlavor;
import com.heima.reggie.dto.DishDto;
import com.heima.reggie.service.CategoryService;
import com.heima.reggie.service.DishFlavorService;
import com.heima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    DishService dishService;
    @Autowired
    DishFlavorService dishFlavorService;
    @Autowired
    CategoryService categoryService;
    @Resource
    RedisTemplate redisTemplate;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info("添加菜品===={}",dishDto.toString());
        dishService.saveDishAndFlavor(dishDto);
        redisTemplate.delete("dish" + dishDto.getCategoryId());

        return R.success("添加成功");

    }

    @GetMapping("/page")
    public R<Page> page(Integer page,Integer pageSize, String name){
        Page<Dish> dishPage = new Page<>(page,pageSize);
        log.info("page==={},pageSize==={}",page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.like(name != null,Dish::getName, name);
        dishLambdaQueryWrapper.orderByDesc(Dish :: getUpdateTime);
        dishService.page(dishPage,dishLambdaQueryWrapper);
        //List<DishDto> dishDtos = dishService.getCategoryName(page,pageSize);
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");
        List<Dish> records = dishPage.getRecords();

        List<DishDto> dishDtos = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(dishDtos);
        log.info("dishDtos================{}",dishDtos.size());
        return R.success(dishDtoPage);

    }

    @GetMapping("{id}")
    public R<DishDto> update01(@PathVariable("id") Long id){

        DishDto dishDto = dishService.getDishDtoById(id);
        log.info("在页面上回显要修改的菜品======{}",dishDto.toString());
        return R.success(dishDto);
    }

    @PutMapping
    public R<String> update02(@RequestBody DishDto dishDto){
        dishService.updateDishAndFlavor(dishDto);
        log.info("修改菜品提交~~~~~~~~~");
        redisTemplate.delete("dish" + dishDto.getCategoryId());
        return R.success("修改成功");
    }

    @DeleteMapping
    public R<String> delete(Long[] ids){
        dishService.deleteByIds(ids);
        log.info("删除菜品~~~~~~~~~");
        return R.success("删除成功");
    }

    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable("status") Integer status ,  Long[] ids){
        log.info("修改菜品售卖状态——————————————————————————————修改后的status={}",status);

        dishService.updateStatusByIdIn(status,ids);
        return R.success("状态修改成功");
    }

//    @GetMapping("/list")
//    public R<List<Dish>> addList(Long categoryId){
//        List<Dish> dishes = dishService.selectDishByCategoryId(categoryId);
//        return R.success(dishes);
//    }
@GetMapping("/list")
public R<List<DishDto>> list(Dish dish){
    List<DishDto> dishDtoList = null;
    String key = "dish" + dish.getCategoryId();
    dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
    if(dishDtoList != null){
        return R.success(dishDtoList);
    }

    //构造查询条件
    LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(dish.getCategoryId() != null ,Dish::getCategoryId,dish.getCategoryId());
    //添加条件，查询状态为1（起售状态）的菜品
    queryWrapper.eq(Dish::getStatus,1);

    //添加排序条件
    queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

    List<Dish> list = dishService.list(queryWrapper);

    dishDtoList = list.stream().map((item) -> {
        DishDto dishDto = new DishDto();

        BeanUtils.copyProperties(item,dishDto);

        Long categoryId = item.getCategoryId();//分类id
        //根据id查询分类对象
        Category category = categoryService.getById(categoryId);

        if(category != null){
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);
        }

        //当前菜品的id
        Long dishId = item.getId();
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
        //SQL:select * from dish_flavor where dish_id = ?
        List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
        dishDto.setFlavors(dishFlavorList);
        return dishDto;
    }).collect(Collectors.toList());

    redisTemplate.opsForValue().set(key,dishDtoList,30, TimeUnit.MINUTES);

    return R.success(dishDtoList);
}



}
